package com.example.permission.common.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtil {

    /**
     * 密钥 base64加密过的
     */
    public static final String SECRET_KEY = "Wb9^vZBjaYiFyhj@dDv!2FXSeEWxJauW";
    /**
     * 发行人
     */
    public static final String ISSUER = "api_info";


    /**
     * 生成token
     *
     * @param claims
     * @return
     */
    public static String genToken(Map<String, String> claims) {
        //使用HMAC256进行加密
        Algorithm algorithm = Algorithm.HMAC256(SECRET_KEY);
        //创建jwt
        JWTCreator.Builder builder = JWT.create().withIssuer(ISSUER);
        //传入参数
        claims.forEach((key, value) -> builder.withClaim(key, value));
        //签名加密
        return builder.sign(algorithm);
    }

    /**
     * 解密jwt
     *
     * @param token
     * @return
     * @throws RuntimeException
     */
    public static Map<String, String> parseToken(String token) {
        Algorithm algorithm = null;
        try {
            //使用HMAC256进行加密
            algorithm = Algorithm.HMAC256(SECRET_KEY);
        } catch (IllegalArgumentException e) {
            log.error("解密jwt失败:{}", e.getMessage());
            return null;
        }
        //解密
        JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
        DecodedJWT jwt = verifier.verify(token);
        Map<String, Claim> map = jwt.getClaims();
        Map<String, String> resultMap = new HashMap<>();
        map.forEach((k, v) -> resultMap.put(k, v.asString()));
        return resultMap;
    }
}
